import axios from 'axios'
import {
  baseUrl
} from '@/config/env'

var $http = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 5000
})

$http.defaults.withCredentials = true
$http.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
$http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

const HEADERS = {
  CONTENT_TYPE: {
    JSON: {
      ContentType: 'application/json; charset=utf-8'
    },
    X_WWW_FORM_URLENCODED: {
      ContentType: 'application/x-www-form-urlencoded'
    }
  }
}

if (process.env.NODE_ENV === 'development') {
  $http.defaults.baseURL = baseUrl
}

// 添加请求拦截器
$http.interceptors.request.use(
  config => {
    const token_key = 'sso_token'
    // 在发送请求之前做些什么
    const token = window.localStorage.getItem(token_key)
    // 把token放到header里面
    if (token) {
      $http.defaults.headers.common['sso_token'] = token
    }
    // 把token放到参数里面
    // console.log("config", config);
    return config
  },

  error => {
    // 对请求错误做些什么
    const res = {}
    res.success = false
    res.status = error.response.status
    res.msg = error.response.message
    return Promise.reject(res)
  })

$http.interceptors.response.use(
  // 对响应数据做些事
  response => {
    let result = response.data
    if (result === null || result === undefined) {
      result = {}
    }
    if (result.success === null || result.success === undefined) {
      result.success = false
    }
    if (result.status === null || result.success === undefined) {
      result.status = response.status
    }
    if (result.msg === null || result.msg === undefined) {
      result.msg = response.message
    }
    return result
  },
  error => {
    let message
    if (!(error && error.response)) {
      message = '连接到服务器失败'
    } else {
      switch (error.response.status) {
        case 400:
          message = '错误请求'
          break
        case 401:
          message = '未授权，请重新登录'
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求错误,未找到该资源'
          break
        case 405:
          message = '请求方法未允许'
          break
        case 408:
          message = '请求超时'
          break
        case 500:
          message = '服务器端出错'
          break
        case 501:
          message = '网络未实现'
          break
        case 502:
          message = '网络错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网络超时'
          break
        case 505:
          message = '不支持该请求'
          break
        default:
          message = '连接错误' + error.response.status
      }
    }
    const result = {}
    result.code = error.response.status
    result.success = false
    result.status = error.response.status
    result.msg = message
    return result
  }
)

export default $http
